/**
 * Copyright (c) 2006 RiseSoft Co.,Ltd  
 * $Header$
 */
package net.risesoft.risebi.collection.web.admin;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.risesoft.risebi.collection.commons.constants.SystemConstants;
import net.risesoft.risebi.collection.commons.miscellaneouse.ExtRecordsMeta;
import net.risesoft.risebi.collection.model.Application;
import net.risesoft.risebi.collection.model.Catalog;
import net.risesoft.risebi.collection.model.DbColumn;
import net.risesoft.risebi.collection.model.EmployeeSoCollection;
import net.risesoft.risebi.collection.model.NotificationReceiver;
import net.risesoft.risebi.collection.model.Query;
import net.risesoft.risebi.collection.model.SoCollection;
import net.risesoft.risebi.collection.model.SoCollectionMember;
import net.risesoft.risebi.collection.model.SoInstance;
import net.risesoft.risebi.collection.model.StatisticalObjectTree;
import net.risesoft.risebi.collection.model.StatisticalObjectTreeNode;
import net.risesoft.risebi.collection.model.User;
import net.risesoft.risebi.collection.service.ApplicationManager;
import net.risesoft.risebi.collection.service.CatalogManager;
import net.risesoft.risebi.collection.service.DbMetaDataManager;
import net.risesoft.risebi.collection.service.DynaBeanManager;
import net.risesoft.risebi.collection.service.EmployeeManager;
import net.risesoft.risebi.collection.service.EmployeeSoCollectionManager;
import net.risesoft.risebi.collection.service.QueryManager;
import net.risesoft.risebi.collection.service.SoCollectionManager;
import net.risesoft.risebi.collection.service.SoCollectionMemberManager;
import net.risesoft.risebi.collection.service.StatisticalObjectTreeManager;
import net.risesoft.risebi.collection.service.StatisticalObjectTreeNodeManager;
import net.risesoft.risebi.collection.service.UserManager;
import net.risesoft.risebi.collection.web.BaseAction;
import net.risesoft.risebi.commons.struts2extension.Trimable;
import net.risesoft.risebi.commons.util.GUID;
import net.risesoft.risebi.commons.util.JSONUtil;
import net.risesoft.risebi.commons.util.PropsUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.apache.commons.beanutils.LazyDynaBean;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;

import com.opensymphony.xwork2.ActionInvocation;

/**
 *
 * @author <a href="mailto: chenjian@risesoft.net">陈健</a>
 * @version $Revision$
 * 
 */
@Namespace("/admin/SoCollectionAction")
public class SoCollectionAction extends BaseAction implements Trimable {	
	private static final long serialVersionUID = -5152718510849660038L;	
	private static Log log = LogFactory.getLog(SoCollectionAction.class);
	
	private String type;
	private String jsonApp;
	private String jsonQuery;
	private String jsonSot;

	private String field; //Ext.ux.plugins.RemoteValidator
	private String value; //Ext.ux.plugins.RemoteValidator
	private String crud;

	private String ModalDialogFieldValue;
	
	private String serviceGuid;
	private String applicationGuid;
	private String applicationName;
	private Boolean addAllSoInstances;
	private Boolean addToSoCollection;
	private String soGuid;
	private String filter;
	private HashMap<String,Object> dynaBean;
	
	private SoCollection soCollection;

	private ApplicationManager applicationManager;
	private SoCollectionManager soCollectionManager;
	private SoCollectionMemberManager soCollectionMemberManager;
	private EmployeeSoCollectionManager employeeSoCollectionManager;
	private StatisticalObjectTreeManager statisticalObjectTreeManager;
	private StatisticalObjectTreeNodeManager statisticalObjectTreeNodeManager;
	private EmployeeManager employeeManager;
	private CatalogManager catalogManager;
	private UserManager userManager;
	private DynaBeanManager dynaBeanManager;
	private QueryManager queryManager;
	private DbMetaDataManager dbMetaDataManager;

	@Action(value="prepareListSocMember",
			results={@Result(name="success", location="/admin/soCollection/listSocMember.jsp")}
	)
	public String prepareListSocMember() throws Exception {
		return SUCCESS;
	}
	
	@Action(value="prepareListSoTreeInstanceMember",
			results={@Result(name="success", location="/admin/soCollection/listSoTreeInstanceMember.jsp")}
	)
	public String prepareListSoTreeInstanceMember() throws Exception {
		return SUCCESS;
	}
	
	@Action(value="getSoTreeInstanceNodes")
	public String getSoTreeInstanceNodes() throws Exception {
		String treeGuid = null;
		try{
			List<SoInstance> list = null;
			if("soTreeInstanceRootNode".equals(this.node)){
				if(this.source.length()==0){
					return "getSoTreeInstanceNodes";
				}else{
					treeGuid = this.source;
				}
			}else{
				treeGuid = this.node;
			}				
			StatisticalObjectTreeNode toNode = null;
			SoInstance fromSoInstance = null;
			StatisticalObjectTreeNode fromNode = null;
			
//			SoTreeInstance manageTreeInstance = new SoTreeInstance();
//			StatisticalObjectTree tree = (StatisticalObjectTree) statisticalObjectTreeManager
//			.getObject(StatisticalObjectTree.class, treeGuid);
//			manageTreeInstance.setTree(tree);
//			
//			manageTreeInstance.addToNode(toNode);
//			manageTreeInstance.setFromNode(tree.getRootNode());
//			if (fromSoInstance != null) {
//				manageTreeInstance.setFromSoInstance(fromSoInstance);
//			}
//			manageTreeInstance.setType(2);
//			
//			list = soCollectionManager.getNextScopeChildren(manageTreeInstance);
			
			JSONArray jsonArray = new JSONArray();
			for(SoInstance t : list){
				boolean isleaf = true;
				int count = soCollectionManager.getCount("select count(*) from Module t where t.parentModule.guid = '" + t.getGuid() + "'");
				if(count>0){
					isleaf = false;
				}
				
				JSONObject jsonObj = new JSONObject();
				jsonObj.element("id", t.getGuid());
				jsonObj.element("text", t.getName());
				jsonObj.element("url", "");
				jsonObj.element("singleClickExpand", true);
				jsonObj.element("qtip", "");
				jsonObj.element("permission", 4);
				jsonObj.element("iconCls", "");
				//jsonObj.element("disabled", !t.getEnabled());
				jsonObj.element("leaf", isleaf);
				jsonArray.add(jsonObj);
			}	
			this.json = jsonArray.toString();			
		}catch(Exception e){
			this.json = "[]";
		} 
		
		return AJAX;
	}
	
	@Action(value="prepareSocList3",
			results={@Result(name="success", location="/admin/soCollection/socList3.jsp")}
	)
	public String prepareSocList3() throws Exception {
		if(this.soCollection.getGuid()==null || this.soCollection.getGuid().trim().length()==0){
			this.soCollection.setTabIndex(100.0);	
			
		}else{
			this.soCollection = (SoCollection)soCollectionManager.getObject(SoCollection.class, this.soCollection.getGuid());
		}
		
		List<StatisticalObjectTree> lst = statisticalObjectTreeManager.getAllByApp(this.soCollection.getAppGuid());
		this.jsonSot = JSONUtil.getJsonString("include","guid,name",lst);

		return SUCCESS;
	}

	@Action(value="prepareSocAddMembers",
			results={@Result(name="success", location="/admin/soCollection/socAddMember.jsp")}
	)
	public String prepareSocAddMembers() throws Exception {
		this.soCollection = (SoCollection)soCollectionManager.getObject(SoCollection.class, node);
		this.applicationGuid = soCollection.getAppGuid();		

		ArrayList al = new ArrayList();		
		List<Catalog> lst = catalogManager.getCatalogWithSoByApp(this.applicationGuid,true);
		for(Catalog a : lst){
			LazyDynaBean ldb = new  LazyDynaBean();	
			ldb.set("guid", a.getGuid());
			ldb.set("name", a.getName());
			al.add(ldb);
		}
		this.json = JSONUtil.getJsonString(null, null, al);	
		
		return SUCCESS;
	}

	@Action(value="prepareSelectSoItems",
			results={@Result(name="success", location="/admin/soCollection/selectSoItems.jsp")}
	)
	public String prepareSelectSoItems() throws Exception {
		this.soCollection = (SoCollection)soCollectionManager.getObject(SoCollection.class, node);
		this.applicationGuid = soCollection.getAppGuid();	
		
		return SUCCESS;
	}
	
	@Action(value="prepareListSocManager",
			results={@Result(name="success", location="/admin/soCollection/listSocManager.jsp")}
	)
	public String prepareListSocManager() throws Exception {
//		SoCollection soc = (SoCollection) soCollectionManager.getObject(SoCollection.class, this.node);
//		String treeGuid = soc.getTreeGuid();
//		if(treeGuid!=null && treeGuid.length()>0){
//			this.type = "3";
//			List<StatisticalObjectTreeNode> lst = statisticalObjectTreeNodeManager.find("from StatisticalObjectTreeNode s where s.statisticalObjectTree.guid='"+treeGuid+"'");
//			this.json = JSONUtil.getJsonString("include", "guid,name", lst);	
//		}else{
//			this.json = "[]";
//		}		
		
		return SUCCESS;
	}

	@Action(value="prepareSocAddManagers",
			results={@Result(name="success", location="/admin/soCollection/socAddManager.jsp")}
	)
	public String prepareSocAddManagers() throws Exception {
		return SUCCESS;
	}

	@Action(value="socAddMembers")
	public String socAddMembers() throws Exception {
		LazyDynaBean ldb = new  LazyDynaBean();
		try{
			SoCollection soc = (SoCollection) soCollectionManager.getObject(SoCollection.class, this.soCollection.getGuid());
			String[] guids = this.source.split(","); 
			for (String guid : guids){
				SoCollectionMember member = new SoCollectionMember();
				member.setSoCollection(soc);
				member.setGuid(new GUID().toString(32));
				member.setSo_guid(this.soGuid);
				member.setSo_instance_guid(guid);
				member.setTabIndex(1d);
				soCollectionMemberManager.saveObject(member);
			}
			ldb.set("success", true);
			ldb.set("reason", "保存成功!");			
			this.json = JSONObject.fromObject(ldb).toString();
		}catch(Exception e){
			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();
		}

		return AJAX;
	}

	@Action(value="socAddManagers")
	public String socAddManagers() throws Exception {
		LazyDynaBean ldb = new  LazyDynaBean();
		try{
			String[] ss = this.json.split(","); 
			for (String s : ss){
				SoCollection socd = (SoCollection) soCollectionManager.getObject(SoCollection.class, this.node);
				User user = (User)userManager.getObject(User.class, s);
				EmployeeSoCollection eso = new EmployeeSoCollection();
				eso.setSoCollection(socd);
				eso.setGuid(new GUID().toString());
				eso.setUser(user);
				employeeSoCollectionManager.saveObject(eso);
			}
			ldb.set("success", true);
			ldb.set("reason", "保存成功!");
			this.json = JSONObject.fromObject(ldb).toString();
		}catch(Exception e){
			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();
		}

		return AJAX;
	}

	@Action(value="prepareSelectSotNode",
			results={@Result(name="success", location="/admin/soCollection/selectSotNode.jsp")}
	)
	public String prepareSelectSotNode() throws Exception {
		String guid = this.ModalDialogFieldValue;
		String Ancestors = this.ModalDialogFieldValue;
		
		if(guid != null && guid.length()>0){
			StatisticalObjectTreeNode sotNode = (StatisticalObjectTreeNode) this.statisticalObjectTreeNodeManager.getObject(StatisticalObjectTreeNode.class, guid);			
			while(true){
				StatisticalObjectTreeNode tempSotNode = sotNode.getParentStatisticalObjectTreeNode();
				if(tempSotNode != null){
					Ancestors = tempSotNode.getGuid() + "," + Ancestors;
					sotNode = tempSotNode;
				}else{
					break;
				}
			}					
			Ancestors = sotNode.getStatisticalObjectTree().getGuid() + "," + Ancestors;	
		}
		this.ModalDialogFieldValue = Ancestors;
		
		return SUCCESS;
	}

	@Action(value="prepareListSoc",
			results={@Result(name="success", location="/admin/soCollection/listSoc.jsp")}
	)
	public String prepareListSoc() throws Exception {
		Application app = (Application)applicationManager.getObject(Application.class, this.applicationGuid);
		this.applicationName = app.getChineseName();
		
		return SUCCESS;
	}

	@Action(value="prepareSocEdit1",
			results={@Result(name="success", location="/admin/soCollection/socEdit1.jsp")}
	)
	public String prepareSocEdit1() throws Exception {
		if(this.soCollection.getGuid()==null || this.soCollection.getGuid().trim().length()==0){
			this.soCollection.setTabIndex(100.0);			
		}else{
			this.soCollection = (SoCollection)soCollectionManager.getObject(SoCollection.class, this.soCollection.getGuid());
		}

		return SUCCESS;
	}

	@Action(value="prepareSocEdit2",
			results={@Result(name="success", location="/admin/soCollection/socEdit2.jsp")}
	)
	public String prepareSocEdit2() throws Exception {
		if(this.soCollection.getGuid()==null || this.soCollection.getGuid().trim().length()==0){
			this.soCollection.setTabIndex(100.0);			
		}else{
			this.soCollection = (SoCollection)soCollectionManager.getObject(SoCollection.class, this.soCollection.getGuid());
		}
		
		List<Query> lst = queryManager.getByApp(this.soCollection.getAppGuid());
		this.jsonQuery = JSONUtil.getJsonString("include","guid,name",lst);

		return SUCCESS;
	}

	@Action(value="prepareSocEdit3",
			results={@Result(name="success", location="/admin/soCollection/socEdit3.jsp")}
	)
	public String prepareSocEdit3() throws Exception {
		if(this.soCollection.getGuid()==null || this.soCollection.getGuid().trim().length()==0){
			this.soCollection.setTabIndex(100.0);			
		}else{
			this.soCollection = (SoCollection)soCollectionManager.getObject(SoCollection.class, this.soCollection.getGuid());
		}
		
		List<StatisticalObjectTree> lst = statisticalObjectTreeManager.getAllByApp(this.soCollection.getAppGuid());
		this.jsonSot = JSONUtil.getJsonString("include","guid,name",lst);

		return SUCCESS;
	}

	@Action(value="validateSoCollectionName")
	public String validateSoCollectionName() throws Exception {
		String guid = this.soCollection.getGuid();
		
		LazyDynaBean ldb = new  LazyDynaBean();		
		if(guid==null || guid.trim().length()==0){
			Integer count = soCollectionManager.getCount("select count(*) from SoCollection t where t.name='" + this.value.trim() + "' and t.application.guid ='" + this.soCollection.getAppGuid() + "'");
			if(count>0){
				ldb.set("success", true);
				ldb.set("valid", false);
				ldb.set("reason", "名称重复。");
			}else{
				ldb.set("success", true);
				ldb.set("valid", true);
				ldb.set("reason", "名称不重复，可以使用。");
			}
		}else{
			Integer count = soCollectionManager.getCount("select count(*) from SoCollection t where t.name='" + this.value.trim() + "' and t.guid !='" + guid + "' and t.application.guid ='" + this.soCollection.getAppGuid() + "'");
			if(count>0){
				ldb.set("success", true);
				ldb.set("valid", false);
				ldb.set("reason", "名称重复。");
			}else{
				ldb.set("success", true);
				ldb.set("valid", true);
				ldb.set("reason", "名称不重复，可以使用。");
			}
		}
		
		this.json = JSONObject.fromObject(ldb).toString();	
		return AJAX;
	}
	
	@Action(value="refreshJson")
	public String refreshJson() throws Exception {
		try{
			if("jsonSoCollection".equalsIgnoreCase(this.whichJson)){
				if(this.soCollection==null){
					this.soCollection = new SoCollection();
				}
				Map map = soCollectionManager.getPagedSoCollection(this.soCollection, "u", "", this.start, this.limit);
				this.json = JSONUtil.getJsonString("include","count,list,guid,name,type,queryGuid,treeGuid,tabIndex",map,"startSotNodeInstanceName","socMembersHQL");		
			}else if("jsonApp4SoCollection".equalsIgnoreCase(this.whichJson)){
				Application app = new Application();
				app.setService(this.getDefaultService());
				Map map = applicationManager.getPagedAppsByServiceWithPermission(app, this.getSessionUser(), start, limit);
				this.json = JSONUtil.getJsonString("include","count,list,guid,chineseName",map);
			}else if("jsonQuery".equalsIgnoreCase(this.whichJson)){
				List<Query> lst = queryManager.getObjects(Query.class);
				this.json = JSONUtil.getJsonString("exclude","params",lst);
			}else if("jsonSot".equalsIgnoreCase(this.whichJson)){
				List<StatisticalObjectTree> lst = statisticalObjectTreeManager.getObjects(StatisticalObjectTree.class);
				this.json = JSONUtil.getJsonString("exclude","sotNodes",lst);
			}else if("jsonEmployee".equalsIgnoreCase(this.whichJson)){
				Map map = employeeManager.getPagedData("from Employee u ", this.start, this.limit, this.sort, this.dir);
				JsonConfig config = new JsonConfig();
				config.setExcludes(new String[]{"department"});
				JSONObject jsonObject = JSONObject.fromObject(map,config);
				this.json = jsonObject.toString();
			}else if("jsonAllSotNodes".equalsIgnoreCase(this.whichJson)){
				ArrayList al = new ArrayList();	
				if(this.active_node_id==null){
					List<StatisticalObjectTree> lst = statisticalObjectTreeManager.getAllOrderByTabIndex();	
					for(StatisticalObjectTree sot : lst){
						int count = 0;
						List<StatisticalObjectTreeNode> lst2 = statisticalObjectTreeNodeManager.getAllBySOT(sot.getGuid());
						if(lst2!=null){
							count = lst2.size();							
						}
						
						LazyDynaBean ldb = new LazyDynaBean();
						ldb.set("guid", sot.getGuid());
						ldb.set("tabIndex", sot.getTabIndex());						
						ldb.set("parentGuid", "");
						ldb.set("_node_type", "sot");
						if(count>0){
							ldb.set("_is_leaf", false);
						}else{
							ldb.set("_is_leaf", true);
						}
						ldb.set("name", sot.getName());
						ldb.set("enabled", sot.getEnabled());
						ldb.set("checked", false);
						al.add(ldb);
					}
					this.json = JSONUtil.getJsonString(null, null, al);					
				}else if("sot".equalsIgnoreCase(this.active_node_type)){
					List<StatisticalObjectTreeNode> lst = statisticalObjectTreeNodeManager.getAllBySOT(this.active_node_id);	
					for(StatisticalObjectTreeNode sotNode : lst){
						int count = 0;
						List<StatisticalObjectTreeNode> lst2 = statisticalObjectTreeNodeManager.getAllBySOTNode(sotNode.getGuid());
						if(lst2!=null){
							count = lst2.size();							
						}
						
						LazyDynaBean ldb = new LazyDynaBean();
						ldb.set("guid", sotNode.getGuid());
						ldb.set("tabIndex", sotNode.getTabIndex());						
						ldb.set("parentGuid", this.active_node_id);
						//ldb.set("parentGuid", sotNode.getStatisticalObjectTree().getGuid());
						ldb.set("_node_type", "sotNode");
						if(count>0){
							ldb.set("_is_leaf", false);
						}else{
							ldb.set("_is_leaf", true);
						}
						ldb.set("name", sotNode.getName());
						ldb.set("checked", false);
						al.add(ldb);
					}
					this.json = JSONUtil.getJsonString(null, null, al);
				}else{
					List<StatisticalObjectTreeNode> lst = statisticalObjectTreeNodeManager.getAllBySOTNode(this.active_node_id);	
					for(StatisticalObjectTreeNode sotNode : lst){
						int count = 0;
						List<StatisticalObjectTreeNode> lst2 = statisticalObjectTreeNodeManager.getAllBySOTNode(sotNode.getGuid());
						if(lst2!=null){
							count = lst2.size();							
						}
						
						LazyDynaBean ldb = new LazyDynaBean();
						ldb.set("guid", sotNode.getGuid());
						ldb.set("tabIndex", sotNode.getTabIndex());						
						ldb.set("parentGuid", sotNode.getParentGuid());
						ldb.set("_node_type", "sotNode");
						if(count>0){
							ldb.set("_is_leaf", false);
						}else{
							ldb.set("_is_leaf", true);
						}
						ldb.set("name", sotNode.getName());
						ldb.set("checked", false);
						al.add(ldb);
					}
					this.json = JSONUtil.getJsonString(null, null, al);
				}				
			}else if("jsonSocMembers".equalsIgnoreCase(this.whichJson)){				
				if(this.addAllSoInstances!=null && this.addAllSoInstances==true){
					try{
						soCollectionMemberManager.execute("delete SoCollectionMember t where t.soCollection.guid='" + node + "'");
						this.soCollection = (SoCollection)soCollectionManager.getObject(SoCollection.class, node);
						
						List<Catalog> soList = catalogManager.getCatalogWithSoByApp(this.soCollection.getAppGuid(),false);
						for(Catalog so : soList){
							String tableName = so.getTableName().trim().toLowerCase();
							List<HashMap<String,Object>> list = dynaBeanManager.getObjects(tableName);
							for(HashMap<String,Object> map : list){
								SoCollectionMember member = new SoCollectionMember();
								member.setSoCollection(this.soCollection);
								member.setGuid(new GUID().toString(32));
								member.setSo_guid(so.getGuid());
								member.setSo_instance_guid(map.get("item_guid").toString());
								member.setTabIndex(1d);
								soCollectionMemberManager.saveObject(member);
							}
						}
					}catch(Exception e){
						e.printStackTrace();
					}
				}
				
				Map<String,List> map = soCollectionMemberManager.getSocMembersBySocGuid(node, start, limit);
				List<SoCollectionMember> list =  map.get("list");
				ArrayList al = new ArrayList();	
				for(SoCollectionMember socm : list){
					LazyDynaBean ldb = new LazyDynaBean();
					ldb.set("guid", socm.getGuid());
					ldb.set("tabIndex", socm.getTabIndex());			
					
					Catalog catalog = (Catalog)catalogManager.getObject(Catalog.class, socm.getSo_guid());
					ldb.set("so_name", catalog.getName());
					ldb.set("so_code", catalog.getCode());
					ldb.set("so_guid", catalog.getGuid());

					ldb.set("soi_guid", socm.getSo_instance_guid());
					String tableName = catalog.getTableName().trim().toLowerCase();
					HashMap<String,Object> dynaBean = (HashMap<String, Object>)dynaBeanManager.getObject(tableName, socm.getSo_instance_guid());
					ldb.set("soi_name", dynaBean.get("item_name"));
					ldb.set("soi_code", dynaBean.get("item_code"));
					
					al.add(ldb);
				}
				map.put("list", al);
				this.json = JSONUtil.getJsonString(null, null, map);				
			}else if("jsonSocManagers".equalsIgnoreCase(this.whichJson)){
				List<EmployeeSoCollection> lst = employeeSoCollectionManager.getBySoCollection(this.node);
				ArrayList al = new ArrayList();	
				for(EmployeeSoCollection e : lst){
					LazyDynaBean ldb = new LazyDynaBean();
					ldb.set("guid", e.getGuid());
					ldb.set("user_guid", e.getUser().getGuid());		
					ldb.set("user_name", e.getUser().getName());		
					ldb.set("user_realName", e.getUser().getRealName());	
					ldb.set("permission", e.getPermission()==null?2:e.getPermission());	
					al.add(ldb);
				}
				this.json = JSONUtil.getJsonString(null, null, al);
			}else if("jsonAllEmployeeUsers".equalsIgnoreCase(this.whichJson)){
				Map map = userManager.getAllEmployeeUser(start, limit);
				this.json = JSONUtil.getJsonString("include", "list,count,guid,name,realName,tabIndex", map);
			}else if("jsonSoItems".equalsIgnoreCase(this.whichJson)){
				Catalog catalog = (Catalog)catalogManager.getObject(Catalog.class, this.soGuid);
				String tableName = catalog.getTableName().trim().toLowerCase();
				
				String where = "";
				if(this.filter!=null){
					where = this.filter.trim();
				}
				if(dynaBean!=null){
					Object item_name = dynaBean.get("item_name");
					Object item_code = dynaBean.get("item_code");
					if(item_name!=null && item_name.toString().trim().length()>0){
						if(where.length()==0){
							where = "t.item_name like '%" + item_name.toString().trim() + "%'";
						}else{
							where += " and t.item_name like '%" + item_name.toString().trim() + "%'";
						}
					}
					if(item_code!=null && item_code.toString().trim().length()>0){							
						if(where.length()==0){
							where = "t.item_code like '%" + item_code.toString().trim() + "%'";
						}else{
							where += " and t.item_code like '%" + item_code.toString().trim() + "%'";
						}
					}
				}

				String condition = "t.item_guid not in (select m.so_instance_guid from SoCollectionMember m where m.so_guid='" + this.soGuid + "' and m.soCollection.guid='" + this.soCollection.getGuid() + "')";
				if(where.length()==0){
					where = condition;
				}else{
					where += " and " + condition;
				}

				Map map = dynaBeanManager.getPagedSoInstances(tableName, "t", "new map(t.catalog_guid as catalog_guid, t.item_guid as item_guid, t.item_code as item_code,t.item_name as item_name,t.tabindex as tabindex)", where, this.start, this.limit);
				//Map map = dynaBeanManager.getPagedSoInstances(tableName, "t", "", where, this.start, this.limit);
				if(this.addToSoCollection!=null && this.addToSoCollection==true){
					SoCollection soc = (SoCollection) soCollectionManager.getObject(SoCollection.class, this.soCollection.getGuid());
					List<Map> newList = (List<Map>)map.get("list");
					for(Map m : newList){
						SoCollectionMember member = new SoCollectionMember();
						member.setSoCollection(soc);
						member.setGuid(new GUID().toString(32));
						member.setSo_guid(this.soGuid);
						member.setSo_instance_guid(m.get("item_guid").toString());
						member.setTabIndex(1d);
						soCollectionMemberManager.saveObject(member);
					}
					this.json = "[]";
				}else{
					this.json = JSONUtil.getJsonString(null, null, map);
				}
			}else if("jsonSoByApp".equalsIgnoreCase(this.whichJson)){
				List<Catalog> lst = catalogManager.getCatalogWithSoByApp(this.applicationGuid,false);
				List newList = new ArrayList();
				for(Catalog t : lst){
					Map map = new HashMap();
					map.put("guid", t.getGuid());
					map.put("name", t.getName());
					newList.add(map);
				}
				this.json = JSONUtil.getJsonString(null,null,newList);

				return AJAX;
			}else if("jsonGroupbyFieldsBySo".equalsIgnoreCase(this.whichJson)){
				List<StatisticalObjectTreeNode> list = statisticalObjectTreeNodeManager.getAllBySoGuid(this.soGuid);
				List newList = new ArrayList();
				for(StatisticalObjectTreeNode n : list){
					Map map = new HashMap();
					
					String fieldName = n.getSelfColumnName().trim().toLowerCase();
					String fieldCaption = "";
					Catalog so = n.getCatalog();
					List<DbColumn> lst1 = dbMetaDataManager.listAllColumns(so.getTableName());
					for(DbColumn f : lst1){
						if(f.getColumn_name().equalsIgnoreCase(fieldName)){
							fieldCaption = f.getComment().trim();
							break;
						}
					}
					
					String parentFieldName = n.getParentColumnName().trim().toLowerCase();
					String parentTableName = n.getParentStatisticalObjectTreeNode().getCatalog().getTableName().trim().toLowerCase();		
					
					map.put("checked", false);
					map.put("fieldName", fieldName);
					map.put("fieldCaption", fieldCaption);
					map.put("parentTableName", parentTableName);
					map.put("parentFieldName", parentFieldName);
					newList.add(map);
				}
				this.json = JSONUtil.getJsonString(null,null,newList);

				return AJAX;
			}else if("jsonGroupbyTreeGrid".equalsIgnoreCase(this.whichJson)){
				String[] str = this.source.split(";");
				if(this.active_node_id==null || this.active_node_id.trim().length()==0){					
					boolean isLeaf = true;
					if(str.length > 1){
						isLeaf = false;
					}
					
					String[] array =  str[0].split(",");
					String parentTableName = array[0];
					String parentFieldName = array[1];
					String fieldName = array[2];
					
					Map map = dynaBeanManager.getPagedSoItems(parentTableName, "t", "", this.start, this.limit);
					List list = (List)map.get("list");
					List newlist = new ArrayList();
					for(Object row : list){
						Map rs = (Map)row;
						HashMap hm = new HashMap(); 
						hm.put("parentId", null);
						hm.put("id", rs.get("item_guid"));
						hm.put("item_name", rs.get("item_name"));
						hm.put("_node_type", parentTableName);
						hm.put("fieldName", fieldName);
						hm.put("fieldValue", rs.get(parentFieldName));
						hm.put("_is_leaf", isLeaf);	
						newlist.add(hm);
					}
					map.put("list", newlist);
					this.json = JSONUtil.getJsonString(null, null, map);
				}else{
					int index = 0;
					for(int i=0; i<str.length; i++){
						if(str[i].contains(this.active_node_type)){
							index = i+1;
							break;
						}
					}

					boolean isLeaf = true;
					if(str.length-1 > index){
						isLeaf = false;
					}
					
					String[] array =  str[index].split(",");
					String parentTableName = array[0];
					String parentFieldName = array[1];
					String fieldName = array[2];					
					
					Map map = dynaBeanManager.getPagedSoItems(parentTableName, "t", "", this.start, this.limit);
					List list = (List)map.get("list");
					List newlist = new ArrayList();
					for(Object row : list){
						Map rs = (Map)row;
						HashMap hm = new HashMap(); 
						hm.put("parentId", this.active_node_id);
						hm.put("id", this.active_node_id + rs.get("item_guid"));
						hm.put("item_name", rs.get("item_name"));
						hm.put("_node_type", parentTableName);
						hm.put("fieldName", fieldName);
						hm.put("fieldValue", rs.get(parentFieldName));
						hm.put("_is_leaf", isLeaf);	
						newlist.add(hm);						
					}
					map.put("list", newlist);
					this.json = JSONUtil.getJsonString(null, null, map);
				}
			}
		}catch(Exception e){
			this.json = "[]";
			e.printStackTrace();
		} 

		return AJAX;
	}

	@Action(value="socEdit")
	public String socEdit() throws Exception {
		LazyDynaBean ldb = new  LazyDynaBean();
		try{
			//排重?
			if(this.soCollection.getGuid()==null || this.soCollection.getGuid().trim().length()==0 || this.soCollection.getGuid().startsWith("NEW")){
				this.soCollection.setGuid(new GUID().toString());
			}
			soCollectionManager.saveObject(this.soCollection);
			
			ldb.set("guid", soCollection.getGuid());
			ldb.set("name", soCollection.getName());
			ldb.set("type", soCollection.getType());
			ldb.set("appGuid", soCollection.getAppGuid());
			ldb.set("queryGuid", soCollection.getQueryGuid());
			ldb.set("treeGuid", soCollection.getTreeGuid());
			ldb.set("tabIndex", soCollection.getTabIndex());
			
			ldb.set("success", true);
			ldb.set("reason", "保存成功!");
			this.json = JSONObject.fromObject(ldb).toString();
		}catch(Exception e){
			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();
		}

		return AJAX;
	}

	@Action(value="insertOrUpdate")
	public String insertOrUpdate() throws Exception {
		LazyDynaBean ldb = new  LazyDynaBean();
		try{
			SoCollection[] ms = (SoCollection[])JSONUtil.stringToArray(json, SoCollection.class);
			String names = "";

			for (SoCollection m : ms){
//				排重
				String sql = "select count(*) from SoCollection u where u.name='"+m.getName()+"' and u.guid !='"+m.getGuid()+"'";
				Integer count = soCollectionManager.getCount(sql);
				if(count>0){
					names += m.getName() + "\r\n";
				}
			}
			if(names.length()>0){
				ldb.set("success", false);
				ldb.set("valid", false);
				ldb.set("reason", "名称重复:\r\n" + names);
				this.json = JSONObject.fromObject(ldb).toString();
				
				return "insertOrUpdate";				
			}
			
			for (SoCollection m : ms){
				if(m.getGuid()==null || m.getGuid().trim().length()==0 || m.getGuid().startsWith("NEW")){
					m.setGuid(new GUID().toString());
				}
				soCollectionManager.saveObject(m);
			}
			
			ldb.set("success", true);
			ldb.set("reason", "保存成功!");
			this.json = JSONObject.fromObject(ldb).toString();
		}catch(Exception e){
			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();
			e.printStackTrace();
		}

		return AJAX;
	}

	@Action(value="insertOrUpdateSocManager")
	public String insertOrUpdateSocManager() throws Exception {
		LazyDynaBean ldb = new  LazyDynaBean();
		try{
			EmployeeSoCollection[] ms = (EmployeeSoCollection[])JSONUtil.stringToArray(json, EmployeeSoCollection.class);
			for (EmployeeSoCollection m : ms){				
				EmployeeSoCollection e = (EmployeeSoCollection)employeeSoCollectionManager.getObject(EmployeeSoCollection.class, m.getGuid());
				e.setPermission(m.getPermission());
				employeeSoCollectionManager.saveObject(e);
			}
			
			ldb.set("success", true);
			ldb.set("reason", "保存成功!");
			this.json = JSONObject.fromObject(ldb).toString();
		}catch(Exception e){
			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();
			e.printStackTrace();
		}

		return AJAX;
	}

	@Action(value="remove")
	public String remove() throws Exception {
		LazyDynaBean ldb = new  LazyDynaBean();
		try{
			soCollectionMemberManager.execute("delete from SoCollectionMember u where u.soCollection.guid='" + this.node + "'");
			employeeSoCollectionManager.execute("delete from EmployeeSoCollection u where u.soCollection.guid='" + this.node + "'");

			soCollectionManager.removeObject(SoCollection.class, node);
			
			ldb.set("success", true);
			ldb.set("reason", "删除成功!");
			this.json = JSONObject.fromObject(ldb).toString();
		}catch(Exception e){
			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();
			e.printStackTrace();
		}
		
		return AJAX;
	}

	@Action(value="removeSocMember")
	public String removeSocMember() throws Exception {
		LazyDynaBean ldb = new  LazyDynaBean();
		try{
			String[] guids = source.split(",");
			for(String guid : guids){
				soCollectionMemberManager.removeObject(SoCollectionMember.class, guid);
			}
			
			ldb.set("success", true);
			ldb.set("reason", "删除成功!");
			this.json = JSONObject.fromObject(ldb).toString();
		}catch(Exception e){
			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();
		}
		
		return AJAX;		
	}

	@Action(value="removeAllSocMembers")
	public String removeAllSocMembers() throws Exception {
		LazyDynaBean ldb = new  LazyDynaBean();
		try{
			soCollectionMemberManager.execute("delete from SoCollectionMember u where u.soCollection.guid='" + this.node + "'");
			
			ldb.set("success", true);
			ldb.set("reason", "删除成功!");
			this.json = JSONObject.fromObject(ldb).toString();
		}catch(Exception e){
			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();
			e.printStackTrace();
		}
		
		return AJAX;		
	}

	@Action(value="removeSocManager")
	public String removeSocManager() throws Exception {
		LazyDynaBean ldb = new  LazyDynaBean();
		try{
			employeeSoCollectionManager.removeObject(EmployeeSoCollection.class, node);
			
			ldb.set("success", true);
			ldb.set("reason", "删除成功!");
			this.json = JSONObject.fromObject(ldb).toString();
		}catch(Exception e){
			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();
			e.printStackTrace();
		}
		
		return AJAX;		
	}

	@Action(value="removeAllSocManagers")
	public String removeAllSocManagers() throws Exception {
		LazyDynaBean ldb = new  LazyDynaBean();
		try{
			employeeSoCollectionManager.execute("delete from EmployeeSoCollection u where u.soCollection.guid='" + this.node + "'");
			
			ldb.set("success", true);
			ldb.set("reason", "删除成功!");
			this.json = JSONObject.fromObject(ldb).toString();
		}catch(Exception e){
			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();
			e.printStackTrace();
		}
		
		return AJAX;		
	}

	/**
	 * ajax获得统计对象集合定义表的数据
	 * 
	 * @return
	 * @throws Exception
	 */
	public String getSoCollections() throws Exception {
		if(soCollection==null)
			soCollection = new SoCollection();
		
		if(limit==0){
			String ps = PropsUtil.getProperty("OrgManageAction_getSoCollections");
			if(ps==null){
				//ps = PropsUtil.getProperties(SystemConstants.REPORT_PAGINGSIZE);
				ps = "10";
			}
			limit = Integer.valueOf(ps); 
		}
		
		Map map = soCollectionManager.getAllSoCollection(soCollection, start, limit);
		int count = (Integer) map.get("count");
		List list = (List) map.get("list");
		
		ExtRecordsMeta erm = new ExtRecordsMeta();
		erm.setResults(count);
		erm.setRows(list);
		
		try {
			JsonConfig config = new JsonConfig();
			config.setExcludes(new String[]{"sotNode"});
			JSONObject jsonObject = JSONObject.fromObject(erm,config);
			json = jsonObject.toString();
			System.out.println(json);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "getSoCollections";
	}
	
	/**
	 *  (non-Javadoc)
	 * @see net.risesoft.commons.struts2extension.Trimable#afterTrim(com.opensymphony.xwork2.ActionInvocation)
	 */
	public void afterTrim(ActionInvocation invocation) {
		
	}

	/**
	 *  (non-Javadoc)
	 * @see net.risesoft.commons.struts2extension.Trimable#preTrim(com.opensymphony.xwork2.ActionInvocation)
	 */
	public boolean preTrim(ActionInvocation invocation) {
		return false;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public String getJsonQuery() {
		return jsonQuery;
	}

	public void setJsonQuery(String jsonQuery) {
		this.jsonQuery = jsonQuery;
	}

	public String getJsonSot() {
		return jsonSot;
	}

	public void setJsonSot(String jsonSot) {
		this.jsonSot = jsonSot;
	}

	public SoCollectionManager getSoCollectionManager() {
		return soCollectionManager;
	}

	public void setSoCollectionManager(
			SoCollectionManager soCollectionManager) {
		this.soCollectionManager = soCollectionManager;
	}

	public SoCollectionMemberManager getSoCollectionMemberManager() {
		return soCollectionMemberManager;
	}

	public void setSoCollectionMemberManager(
			SoCollectionMemberManager soCollectionMemberManager) {
		this.soCollectionMemberManager = soCollectionMemberManager;
	}

	public EmployeeSoCollectionManager getEmployeeSoCollectionManager() {
		return employeeSoCollectionManager;
	}

	public void setEmployeeSoCollectionManager(
			EmployeeSoCollectionManager employeeSoCollectionManager) {
		this.employeeSoCollectionManager = employeeSoCollectionManager;
	}

	public QueryManager getQueryManager() {
		return queryManager;
	}

	public void setQueryManager(QueryManager queryManager) {
		this.queryManager = queryManager;
	}

	public StatisticalObjectTreeManager getStatisticalObjectTreeManager() {
		return statisticalObjectTreeManager;
	}

	public void setStatisticalObjectTreeManager(
			StatisticalObjectTreeManager statisticalObjectTreeManager) {
		this.statisticalObjectTreeManager = statisticalObjectTreeManager;
	}

	public EmployeeManager getEmployeeManager() {
		return employeeManager;
	}

	public void setEmployeeManager(EmployeeManager employeeManager) {
		this.employeeManager = employeeManager;
	}

	public SoCollection getSoCollection() {
		return soCollection;
	}

	public void setSoCollection(SoCollection soCollection) {
		this.soCollection = soCollection;
	}

	public String getModalDialogFieldValue() {
		return ModalDialogFieldValue;
	}

	public void setModalDialogFieldValue(String modalDialogFieldValue) {
		ModalDialogFieldValue = modalDialogFieldValue;
	}

	public StatisticalObjectTreeNodeManager getStatisticalObjectTreeNodeManager() {
		return statisticalObjectTreeNodeManager;
	}

	public void setStatisticalObjectTreeNodeManager(
			StatisticalObjectTreeNodeManager statisticalObjectTreeNodeManager) {
		this.statisticalObjectTreeNodeManager = statisticalObjectTreeNodeManager;
	}

	public CatalogManager getCatalogManager() {
		return catalogManager;
	}

	public void setCatalogManager(CatalogManager catalogManager) {
		this.catalogManager = catalogManager;
	}

	public DynaBeanManager getDynaBeanManager() {
		return dynaBeanManager;
	}

	public void setDynaBeanManager(DynaBeanManager dynaBeanManager) {
		this.dynaBeanManager = dynaBeanManager;
	}

	public UserManager getUserManager() {
		return userManager;
	}

	public void setUserManager(UserManager userManager) {
		this.userManager = userManager;
	}

	public String getJsonApp() {
		return jsonApp;
	}

	public void setJsonApp(String jsonApp) {
		this.jsonApp = jsonApp;
	}

	public ApplicationManager getApplicationManager() {
		return applicationManager;
	}

	public void setApplicationManager(ApplicationManager applicationManager) {
		this.applicationManager = applicationManager;
	}

	public String getApplicationGuid() {
		return applicationGuid;
	}

	public void setApplicationGuid(String applicationGuid) {
		this.applicationGuid = applicationGuid;
	}

	public String getServiceGuid() {
		return serviceGuid;
	}

	public void setServiceGuid(String serviceGuid) {
		this.serviceGuid = serviceGuid;
	}

	public String getApplicationName() {
		return applicationName;
	}

	public void setApplicationName(String applicationName) {
		this.applicationName = applicationName;
	}

	public String getField() {
		return field;
	}

	public void setField(String field) {
		this.field = field;
	}

	public String getValue() {
		return value;
	}

	public void setValue(String value) {
		this.value = value;
	}

	public String getCrud() {
		return crud;
	}

	public void setCrud(String crud) {
		this.crud = crud;
	}

	public Boolean getAddAllSoInstances() {
		return addAllSoInstances;
	}

	public void setAddAllSoInstances(Boolean addAllSoInstances) {
		this.addAllSoInstances = addAllSoInstances;
	}

	public String getSoGuid() {
		return soGuid;
	}

	public void setSoGuid(String soGuid) {
		this.soGuid = soGuid;
	}

	public String getFilter() {
		return filter;
	}

	public void setFilter(String filter) {
		this.filter = filter;
	}

	public HashMap<String, Object> getDynaBean() {
		return dynaBean;
	}

	public void setDynaBean(HashMap<String, Object> dynaBean) {
		this.dynaBean = dynaBean;
	}

	public DbMetaDataManager getDbMetaDataManager() {
		return dbMetaDataManager;
	}

	public void setDbMetaDataManager(DbMetaDataManager dbMetaDataManager) {
		this.dbMetaDataManager = dbMetaDataManager;
	}

	public Boolean getAddToSoCollection() {
		return addToSoCollection;
	}

	public void setAddToSoCollection(Boolean addToSoCollection) {
		this.addToSoCollection = addToSoCollection;
	}
	
}
